package com.school.accessdoor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.mhuang.school.starter.minio.core.MinioFrame;
import com.mhuang.school.starter.minio.util.ToolUtil;
import com.school.device.config.DahuaCofig;
import com.school.device.config.DoorConfig;
import com.school.device.dynamic.DvIntellifHikvisonDevice;
import com.school.device.util.DataConvertUtil;
import com.school.device.util.JsonUtil;
import com.school.door.AiAccessDoorRecord;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@SuppressWarnings("unused")
@Slf4j
@Component
public class AccessDoorSchedule {
	@Autowired
	private DoorConfig doorConfig;
	
	@Autowired
	private DahuaCofig dahuaCofig;
	
	@Autowired
	private MinioFrame minioFrame;
	
	private final TaskScheduler taskScheduler;
    private ScheduledFuture<?> scheduledFuture;
    
    
	private final static Map<String, String> userIdFaces=new ConcurrentHashMap<String, String>();  
	private final static Map<String,Long> deviceIdDates=new ConcurrentHashMap<String, Long>();	
    

    public AccessDoorSchedule(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }
	
	
    @PostConstruct
    public void init() {
        scheduledFuture = taskScheduler.schedule(() -> {//此处为执行任务
        	List<DvIntellifHikvisonDevice> devices= getDevices().stream().filter(item->(item.getDeviceType()==5)).collect(Collectors.toList());
        	//获取设备ips
        	String deviceIps=devices.stream().filter(item->(item.getDeviceType()==5)).map(DvIntellifHikvisonDevice::getDeviceIp).filter(ip->ToolUtil.isNotEmpty(ip)).collect(Collectors.joining(","));//可能发生变化
			log.info("门禁设备定时任务开始 {}", deviceIps);
        	if(ToolUtil.isNotEmpty(deviceIps)) {
            	//获取最近状态
            	getUserIdDatas(deviceIps);
            	//执行单个单个拉取
            	List<Map<String, Object>> result=new ArrayList<Map<String,Object>>();
            	for(DvIntellifHikvisonDevice device:devices) {
            		String deviceIp=device.getDeviceIp();
            		Long latestDate=deviceIdDates.get(deviceIp);
            		if(latestDate==null)
            			latestDate=0l;
            		else
            			latestDate=latestDate/1000;
            		//以前的版本
            		//List<Map<String, Object>> datas=HttpCaptureUtil.assemble(minioFrame, userIdFaces, device.getDeviceIp(), device.getAccount(), device.getPassword(),200, latestDate);
            		try {
						List<Map<String, Object>> datas = HttpCaptureUtil.assemble(minioFrame, device.getDeviceIp(), device.getAccount(), device.getPassword(), 200, latestDate, device.getDoorDirection());
						//List<Map<String, Object>> datas=getDatas(device);
						if (datas != null) {
							for (Map<String, Object> data : datas) {
								data.put("id", getUUId32());
								data.put("tenantId", device.getSchoolId());
								data.put("deviceIp", device.getDeviceIp());
								data.put("deviceName", device.getDeviceName());
								data.put("deviceType", device.getDeviceType());
								data.put("deviceAddress", device.getDeviceAddress());
								data.put("createTime", getCurrentTimestamp());
								data.put("updateTime", getCurrentTimestamp());
								result.add(data);
							}
							sendStatus(device.getDeviceIp(), 1);
						}
					}catch (Exception e) {
						log.info("获取门禁记录失败:ip:{}, account:{},pass:{}", device.getDeviceIp(), device.getAccount(), device.getPassword());
						log.info("获取门禁记录失败:{}", e);
					}
            		try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
            	}
            	if(result!=null && result.size() > 0) {
            		sendData(result);
            		log.info("一次定时任务执行完成,写入数据:"+result.size());
            	}
        	}
        }, new CronTrigger(doorConfig.getCronExpress())); // 每5秒执行一次
    }
    
	public static String getUUId32() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	public static Long getCurrentTimestamp() {
		return System.currentTimeMillis();
	}
    
	//发送数据
	private void sendData(List<Map<String, Object>> datas) {
		if(datas!=null && datas.size()>0) {
			log.info("【DOOR推送响应】-->{}",JsonUtil.toString(datas));			
			HttpResponse res = HttpRequest.post(doorConfig.getPushUrl()).body(JsonUtil.toString(datas)).execute();
			log.info("【DOOR推送响应】-->{}", res.body());			
		}
	}
    
	//获取设备最近状态
	private List<AiAccessDoorRecord> getLatestStatus(String deviceIps){
		if (ToolUtil.isEmpty(deviceIps)) {
			System.err.println("拉取不到相关的门禁设备");
			log.error("拉取不到相关的门禁设备");
			return null;
		}
		HttpResponse response = HttpRequest.get(doorConfig.getCheckUrl()+"?deviceIps="+deviceIps).execute();
		if (response.isOk()) {
			String body = response.body();
			if (ToolUtil.isNotEmpty(body)) {
				Map<String, Object> result = JsonUtil.toMap(body);
				if (DataConvertUtil.getObjectStr(result, "respCode").equalsIgnoreCase("10000000"))
					return JsonUtil.toBeans(JSON.toJSONString(result.get("data")), AiAccessDoorRecord.class);
			}
		}
		System.err.println("请检查连接设备端口");
		log.error("请检查连接设备端口");
		return null;		
	}
    
	private void getUserIdDatas(String deviceIps){
		List<AiAccessDoorRecord> datas=getLatestStatus(deviceIps);
		if(datas==null)
			return;
		datas.stream().forEach((item)->{
			String deviceId=item.getDeviceIp();
			Long cardTime=item.getCardTime();
			if(!deviceIdDates.containsKey(deviceId)) {
				deviceIdDates.put(deviceId, cardTime);
			}else {
				Long ocardTime=deviceIdDates.get(deviceId);
				if(cardTime.compareTo(ocardTime)>0)
					deviceIdDates.put(deviceId, cardTime);
			}
		});	
	}
    
    //获取所有设备(需要间隔5分钟)
	private List<DvIntellifHikvisonDevice> getDevices() {
		String deviceIpUrl=dahuaCofig.getDeviceipUrl();
		if (ToolUtil.isEmpty(deviceIpUrl)) {
			System.err.println("拉取设备端口接口为空");
			log.error("拉取设备端口接口为空");
			return null;
		}
		HttpResponse response = HttpRequest.get(deviceIpUrl).execute();
		if (response.isOk()) {
			String body = response.body();
			if (ToolUtil.isNotEmpty(body)) {
				Map<String, Object> result = JsonUtil.toMap(body);
				if (DataConvertUtil.getObjectStr(result, "respCode").equalsIgnoreCase("10000000"))
					return JsonUtil.toBeans(JSON.toJSONString(result.get("data")), DvIntellifHikvisonDevice.class);
			}
		}
		System.err.println("请检查连接设备端口");
		log.error("请检查连接设备端口");
		return null;
	}
 
	//发送状态
	private void sendStatus(String ip,Integer status){
		//Integer status=ipStatus.get(ip);
		log.info("【DOOR推送状态】-->ip:{},status{}",ip,(status==null || status==0)?"离线":"在线");
		if(status!=null) {
			HttpResponse res = HttpRequest.get(doorConfig.getStatusUrl()+"?ip="+ip+"&status="+status).execute();
			log.info("【DOOR推送状态响应】-->{}", res.body());			
		}
	}

    @PreDestroy
    public void destroy() {
        if (scheduledFuture != null) 
            scheduledFuture.cancel(true);
    }
	
}
